package com.kbbywyclient.ui.activity;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.kbbywyclient.R;
import com.kbbywyclient.data.entity.CreditCardTableMenu;
import com.kbbywyclient.data.entity.Event;
import com.kbbywyclient.data.entity.LoansTableMenu;
import com.kbbywyclient.data.entity.ResultInfoCre;
import com.kbbywyclient.data.entity.TabledBuy;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.CustomerTableModule;
import com.kbbywyclient.presenter.CustomerTablePresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.adapter.CustomerTableAdapter;
import com.kbbywyclient.ui.adapter.MenuCreditCardAdapter;
import com.kbbywyclient.ui.adapter.MenuEducationAdapter;
import com.kbbywyclient.ui.adapter.MenuUnitPropertyAdapter;
import com.kbbywyclient.ui.contarct.CustomerTableContarct;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.ViewUtils;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomDialog;
import com.kbbywyclient.widget.CustomPopwin;
import com.kbbywyclient.widget.CustomToolBar;
import com.kbbywyclient.widget.GetMoreListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Description:
 * Created by FHW
 * on 2017/4/14
 */

public class CustomerTableActivity extends BaseActivity implements CustomerTableContarct.View {

    @BindView(R.id.v_toolbar)
    CustomToolBar v_toolbar;
    @BindView(R.id.ptr_view)
    PtrClassicFrameLayout ptr_view;
    @BindView(R.id.lv_customer_table)
    GetMoreListView lv_customer_table;

    @BindView(R.id.ll_view)
    LinearLayout ll_view;
    @BindView(R.id.ll_toolbar)
    LinearLayout ll_toolbar;
    @BindView(R.id.tv_card_holding)
    TextView tv_card_holding;
    @BindView(R.id.tv_culture)
    TextView tv_culture;
    @BindView(R.id.tv_info_provid)
    TextView tv_info_provid;
    @BindView(R.id.iv_card_holding)
    ImageView iv_card_holding;
    @BindView(R.id.iv_culture)
    ImageView iv_culture;
    @BindView(R.id.iv_info_provid)
    ImageView iv_info_provid;


    @Inject
    CustomerTablePresenter customerTablePresenter;

    private CustomerTableAdapter customerTableAdapter = null;

    private String CompanyID = "";
    private String CompanyTypeID = "";
    private String creditCard = "";
    private String dist = "";//城市区域ID
    private String education = "0";//学历ID
    //    private String personalInformation = "";//提供资料ID
    private String unitNature = "0";//单位性质ID

    private int mType = -1;

    private CustomPopwin popwin = null;

    private boolean isFirstLoad = true;

    private List<LoansTableMenu.CreditCardBean> creditCardBeanList = null;
    private MenuCreditCardAdapter menuCreditCardAdapter = null;

    private List<CreditCardTableMenu.EducationBean> educationBeanList = null;
    private MenuEducationAdapter menuEducationAdapter = null;

    //    private List<CreditCardTableMenu.PersonalInformationBean> personalInformationBeanList = null;
//    private MenuInformationAdapter menuInformationAdapter = null;
    private List<CreditCardTableMenu.UnitNatureBean> unitNatureBeanList = null;
    private MenuUnitPropertyAdapter menuUnitPropertyAdapter = null;

    private List<ResultInfoCre> resultInfoList = null;

    private int applyCreditCardID = -1;
    private String applyCreditCardSN = "";

    private int mPosition = 0;

    private CustomDialog dialog;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_customer_table;
    }

    @OnClick({R.id.ll_card_holding, R.id.ll_culture, R.id.ll_info_provid})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_card_holding://持卡情况
                mType = 0;
                showView(mType);
                showPop(view);
                if (!isFirstLoad && creditCardBeanList.size() < 0) {
                    customerTablePresenter.getCreditCardMenu(PreUtils.getUser(this).getSalesID() + "");
                }
                break;
            case R.id.ll_culture://文化程度
                mType = 1;
                showView(mType);
                showPop(view);
                if (!isFirstLoad && educationBeanList.size() < 0) {
                    customerTablePresenter.getCreditCardMenu(PreUtils.getUser(this).getSalesID() + "");
                }
                break;
            case R.id.ll_info_provid://资料提供
                mType = 2;
                showView(mType);
                showPop(view);
                if (!isFirstLoad && unitNatureBeanList.size() < 0) {
                    customerTablePresenter.getCreditCardMenu(PreUtils.getUser(this).getSalesID() + "");
                }
                break;
        }
    }

    private void showPop(View view) {
        View proView = LayoutInflater.from(this).inflate(R.layout.pop_customer_table, null, false);
        ListView lv_card_holding = (ListView) proView.findViewById(R.id.lv_card_holding);
        ListView lv_culture = (ListView) proView.findViewById(R.id.lv_culture);
        ListView lv_info_provid = (ListView) proView.findViewById(R.id.lv_info_provid);

        View v_dimess = proView.findViewById(R.id.v_dimess);

        lv_card_holding.setVisibility(View.GONE);
        lv_culture.setVisibility(View.GONE);
        lv_info_provid.setVisibility(View.GONE);

        if (popwin == null) {
            popwin = new CustomPopwin(this, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f);
        }
        switch (mType) {
            case 0:
                lv_card_holding.setVisibility(View.VISIBLE);
                if (creditCardBeanList != null) {
                    setCreditCardAdapter(lv_card_holding);
                }
                break;
            case 1:
                lv_culture.setVisibility(View.VISIBLE);
                if (educationBeanList != null) {
                    setEducationAdapter(lv_culture);
                }
                break;
            case 2:
                lv_info_provid.setVisibility(View.VISIBLE);
                if (unitNatureBeanList != null) {
                    setInformationAdapter(lv_info_provid);
                }
                break;
        }
        popwin.setFocusable(false);
        popwin.setContentView(proView);
        popwin.showAsDropDown(view, 0, 0);
        popwin.setOnDismissListener(() -> {
            setTextType();
        });
        lv_card_holding.setOnItemClickListener((parent, view13, position, id) -> {
            popwin.dismiss();
            for (int i = 0; i < creditCardBeanList.size(); i++) {
                creditCardBeanList.get(i).setCheck(false);
                if (position == i) {
                    creditCardBeanList.get(i).setCheck(true);
                    creditCard = creditCardBeanList.get(i).getCode();
                    ViewUtils.setText(tv_card_holding, creditCardBeanList.get(i).getName());
                }
            }
            ptr_view.autoRefresh();
        });

        lv_culture.setOnItemClickListener((parent, view1, position, id) -> {
            popwin.dismiss();
            for (int i = 0; i < educationBeanList.size(); i++) {
                educationBeanList.get(i).setCheck(false);
                if (position == i) {
                    educationBeanList.get(i).setCheck(true);
                    education = educationBeanList.get(i).getID() + "";
                    ViewUtils.setText(tv_culture, educationBeanList.get(i).getName());
                }
            }
            ptr_view.autoRefresh();
        });
        lv_info_provid.setOnItemClickListener((parent, view12, position, id) -> {
            popwin.dismiss();
//            for (int i = 0; i < personalInformationBeanList.size(); i++) {
//                personalInformationBeanList.get(i).setCheck(false);
//                if (position == i) {
//                    personalInformationBeanList.get(i).setCheck(true);
//                    personalInformation = personalInformationBeanList.get(i).getCode();
//                    ViewUtils.setText(tv_info_provid, personalInformationBeanList.get(i).getName());
//                }
//            }
            for (int i = 0; i < unitNatureBeanList.size(); i++) {
                unitNatureBeanList.get(i).setCheck(false);
                if (position == i) {
                    unitNatureBeanList.get(i).setCheck(true);
//                    unitNature = unitNatureBeanList.get(i).getCode();
                    unitNature = unitNatureBeanList.get(i).getID() + "";
                    ViewUtils.setText(tv_info_provid, unitNatureBeanList.get(i).getName());
                }
            }
            ptr_view.autoRefresh();
        });

        v_dimess.setOnClickListener(v -> popwin.dismiss());

    }

    private void setCreditCardAdapter(ListView lv) {
        menuCreditCardAdapter = new MenuCreditCardAdapter(this, R.layout.item_menu_purpose, creditCardBeanList);
        lv.setAdapter(menuCreditCardAdapter);
    }

    private void setEducationAdapter(ListView lv) {
        menuEducationAdapter = new MenuEducationAdapter(this, R.layout.item_menu_purpose, educationBeanList);
        lv.setAdapter(menuEducationAdapter);
    }

    private void setInformationAdapter(ListView lv) {
//        menuInformationAdapter = new MenuInformationAdapter(this, R.layout.item_menu_purpose, personalInformationBeanList);
//        lv.setAdapter(menuInformationAdapter);
        menuUnitPropertyAdapter = new MenuUnitPropertyAdapter(this, R.layout.item_menu_purpose, unitNatureBeanList);
        lv.setAdapter(menuUnitPropertyAdapter);
    }

    private void showView(int type) {
        setTextType();
        switch (type) {
            case 0:
                tv_card_holding.setTextColor(getResources().getColor(R.color.color_14C095));
                iv_card_holding.setBackgroundResource(R.mipmap.icon_table_up);
                break;
            case 1:
                tv_culture.setTextColor(getResources().getColor(R.color.color_14C095));
                iv_culture.setBackgroundResource(R.mipmap.icon_table_up);
                break;
            case 2:
                tv_info_provid.setTextColor(getResources().getColor(R.color.color_14C095));
                iv_info_provid.setBackgroundResource(R.mipmap.icon_table_up);
                break;
        }
    }

    private void setTextType() {
        tv_card_holding.setTextColor(getResources().getColor(R.color.color_212121));
        tv_culture.setTextColor(getResources().getColor(R.color.color_212121));
        tv_info_provid.setTextColor(getResources().getColor(R.color.color_212121));
        iv_card_holding.setBackgroundResource(R.mipmap.icon_table_dwon);
        iv_culture.setBackgroundResource(R.mipmap.icon_table_dwon);
        iv_info_provid.setBackgroundResource(R.mipmap.icon_table_dwon);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("客户申请表");
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        resultInfoList = new ArrayList<>();

        creditCardBeanList = new ArrayList<>();
        educationBeanList = new ArrayList<>();
//        personalInformationBeanList = new ArrayList<>();
        unitNatureBeanList = new ArrayList<>();

        CompanyID = getIntent().getStringExtra("CompanyID");
        CompanyTypeID = getIntent().getStringExtra("CompanyTypeID");

        v_toolbar.setLeftViewOnClickLinster(v -> finish());
        v_toolbar.setRightViewOnClickLinster(v -> {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("type", 3);
            ActivitySkipUtil.skipAnotherActivity(this, DiscountActivity.class, map);
        });

        //加载更多
        lv_customer_table.setOnGetMoreListener(() -> {
            refresh(false);
        });
        lv_customer_table.setOnItemClickListener((parent, view, position, id) -> {
            if (position < resultInfoList.size() && resultInfoList.size() > 0) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("ApplyCreditCardID", resultInfoList.get(position).getApplyCreditCardID());
                map.put("ApplyCreditCardSN", resultInfoList.get(position).getApplyCreditCardSN());
                map.put("position", position);
                //信用卡客户申请表大数据埋点
                Map<String, String> bigDataMap = new HashMap<>();
                bigDataMap.put("pageNo", "信用卡业务");
                bigDataMap.put("order_id", String.valueOf(applyCreditCardID));
                bigDataMap.put("order_name", applyCreditCardSN);
                bigDataMap.put("behavior", "cbeibei_loan_product_click");
                customerTablePresenter.bigDataBuried(bigDataMap);
                ActivitySkipUtil.skipAnotherActivity(this, CreditTableDetailActivity.class, map);
            }
        });

        lv_customer_table.setOnSileListener(new GetMoreListView.OnSileListener() {
            @Override
            public void onSlideUp(int direction) {
                ll_view.setVisibility(View.GONE);
                ViewUtils.setViewAnim(direction, ll_toolbar);
            }

            @Override
            public void onSlideDwon(int direction) {
                ll_view.setVisibility(View.INVISIBLE);
                ViewUtils.setViewAnim(direction, ll_toolbar);
            }
        });

    }

    @Override
    public void initData() {
        ptr_view.setLastUpdateTimeRelateObject(this);
        ptr_view.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                lv_customer_table.setHasMore();
                refresh(true);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
        // the following are default settings
        ptr_view.setResistance(1.7f);
        ptr_view.setRatioOfHeaderHeightToRefresh(1.2f);
        ptr_view.postDelayed(() -> ptr_view.autoRefresh(), 100);
    }

    private void refresh(boolean isClean) {
        customerTablePresenter.getCreditCardOrders(isClean, PreUtils.getUser(this).getSalesID() + ""
                , dist, education, unitNature, creditCard);
    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getCustomerTableComponent(new CustomerTableModule(this)).inject(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 购买 回调
     *
     * @param notifyCustomerTable
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event.NotifyCustomerTable notifyCustomerTable) {
        resultInfoList.remove(notifyCustomerTable.getPosition());
        customerTableAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event.CustomerTableBuy customerTableBuy) {
        applyCreditCardID = resultInfoList.get(customerTableBuy.getPosition()).getApplyCreditCardID();
        applyCreditCardSN = resultInfoList.get(customerTableBuy.getPosition()).getApplyCreditCardSN();
        mPosition = customerTableBuy.getPosition();
        customerTablePresenter.getApplyCreditCardBuy(PreUtils.getUser(CustomerTableActivity.this).getSalesID() + ""
                , applyCreditCardID + "", applyCreditCardSN
                , "1");
    }

    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    @Override
    public void loadSucCustomerTable(List<ResultInfoCre> resultInfoList) {
        ptr_view.refreshComplete();
        if (isFirstLoad) {
            ll_view.setVisibility(View.INVISIBLE);
            customerTablePresenter.getCreditCardMenu(PreUtils.getUser(this).getSalesID() + "");
        }
    }

    @Override
    public void loadFaiCustomerTable(String errorMsg) {
        ptr_view.refreshComplete();
        lv_customer_table.getMoreComplete();
    }

    @Override
    public void setAdapterOrNotify(List<ResultInfoCre> mResultInfoList) {
        if (resultInfoList.size() > 0) {
            resultInfoList.clear();
        }
        resultInfoList.addAll(mResultInfoList);
        if (customerTableAdapter == null) {
            customerTableAdapter = new CustomerTableAdapter(this, R.layout.item_customer_table, resultInfoList);
            lv_customer_table.setAdapter(customerTableAdapter);
        } else {
            customerTableAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void setNoMore() {
        lv_customer_table.setNoMore();
    }

    @Override
    public void setMoreComplete() {
        lv_customer_table.getMoreComplete();
    }

    @Override
    public void loadSucMenu(CreditCardTableMenu creditCardTableMenu) {

        LoansTableMenu.CreditCardBean creditCardBean = new LoansTableMenu.CreditCardBean();
        creditCardBean.setName("不限");
        creditCardBean.setCode("");
        creditCardBean.setCheck(true);
        creditCardBeanList.add(creditCardBean);
        creditCardBean = new LoansTableMenu.CreditCardBean();
        creditCardBean.setName("无信用卡");
        creditCardBean.setCode("0");
        creditCardBeanList.add(creditCardBean);
        creditCardBean = new LoansTableMenu.CreditCardBean();
        creditCardBean.setName("持有信用卡");
        creditCardBean.setCode("1");
        creditCardBeanList.add(creditCardBean);

        educationBeanList.addAll(creditCardTableMenu.getEducation());
        CreditCardTableMenu.EducationBean educationBean = new CreditCardTableMenu.EducationBean();
        educationBean.setName("不限");
        educationBean.setCheck(true);
        educationBeanList.add(0, educationBean);

        unitNatureBeanList.addAll(creditCardTableMenu.getUnitNature());
        CreditCardTableMenu.UnitNatureBean unitNatureBean = new CreditCardTableMenu.UnitNatureBean();
        unitNatureBean.setName("不限");
        unitNatureBean.setCheck(true);
        unitNatureBeanList.add(0, unitNatureBean);


        if (!isFirstLoad) {
            showPop(ll_toolbar);
        }
        isFirstLoad = false;

    }

    @Override
    public void loadFaiMenu(String errorMsg) {

    }

    @Override
    public void loadSucCreditCarBuy(TabledBuy tabledBuy, String buyType) {
        if (StringUtil.isNotEmpty(buyType)) {//检验

            dialog = new CustomDialog(this, R.style.Customdialog, "提示", "是否确定购买？\n所需积分：" + tabledBuy.getScore() + " 积分"
                    , new CustomDialog.ButtonListener() {
                @Override
                public void left() {
                    dialog.dismiss();
                }

                @Override
                public void right() {
                    customerTablePresenter.getApplyCreditCardBuy(PreUtils.getUser(CustomerTableActivity.this).getSalesID() + ""
                            , applyCreditCardID + "", applyCreditCardSN
                            , "");

                    dialog.dismiss();
                }
            }, getString(R.string.cancel), getString(R.string.determine));
            dialog.show();
        } else {//购买
            setScreenAction("购买", "信用卡-客户申请表-购买");
            ToastUtil.showShort("购买成功！可在\"已购买客户\"中管理 ");
            resultInfoList.remove(mPosition);
            customerTableAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void loadFaiCreditCarBuy(String errorMsg) {
        if (errorMsg.equals("您的剩余积分不够,请充值!")) {
            dialog = new CustomDialog(this, R.style.Customdialog, "提示", errorMsg
                    , new CustomDialog.ButtonListener() {
                @Override
                public void left() {
                    dialog.dismiss();
                }

                @Override
                public void right() {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("CompanyID", CompanyID);
                    map.put("CompanyTypeID", CompanyTypeID);
                    ActivitySkipUtil.skipAnotherActivity(CustomerTableActivity.this, MineScoreActivity.class, map);
                    dialog.dismiss();
                }
            }, getString(R.string.cancel), getString(R.string.determine));
            dialog.show();
        }
    }
}
